package Demo;

import java.util.concurrent.BlockingDeque;
import java.util.concurrent.LinkedBlockingDeque;

class MyThreadPool{
    private BlockingDeque<Runnable> blockingDeque = new LinkedBlockingDeque();
    //往阻塞队列里面添加元素
    public void submit(Runnable runnable) throws InterruptedException {
        blockingDeque.put(runnable);
    }
    //用构造方法构造个数为n个线程的线程池
    public MyThreadPool(int n ){
        for (int i = 0; i < n; i++) {
            Thread t = new Thread(()->{
                try {
                    while (true) {
                        blockingDeque.take().run();
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            });
            //构造n个线程然后启动
            t.start();
        }

    }
}
public class Test {
    public static void main(String[] args) throws InterruptedException {
        //为线程池构造10个线程
        MyThreadPool pool = new MyThreadPool(10);
        //为线程池分配任务
        for (int i = 0; i < 1000; i++) {
            int number = i;
            pool.submit(new Runnable() {
                @Override
                public void run() {
                    System.out.println("任务:"+ number);
                }
            });
        }
    }
}
